using System;
using System.IO;
using System.Web;
using System.Web.UI;

using Actions.Security;

namespace Actions.Connectors
{
	/// <summary>
	/// Web dispatcher. This class control inteface between Manager and output stream
	/// </summary>
	public class WebConnector : Page, IConnector
	{
		public WebConnector()
		{}
				
		protected void Page_Load(Object sender,EventArgs args)
		{					
			execute();
		}		
		
		public void execute()
		{
			Manager.i.execute(this);
		}
		
		public string getInputParam(string name)
		{
			string res = this.Request.Form[name];
			
			if(res == null || res.Length == 0) {
				res = this.Request.Params[name];
			}
			return res;
		}
		
		public object getSessionParam(string name)
		{
			return this.Session[name] as object;
		}
		
		public void setSessionParam(string name, object obj)
		{
			try {
				this.Session.Add(name, obj);				
			} catch(Exception e) {
				Manager.i.error("WebConnector", e);
			}
		}
				
		public string getInputParamWithMem(string name, string savePrefix, string valueDefault)
		{
			string 	value = getInputParam(name);
			
			if(value.Length > 0) {
				setSessionParam(savePrefix + name, (object) value);
			} else {
				value = (string) getSessionParam(savePrefix + name);				
				if(value.Length == 0) {
					value = valueDefault;
				}
			}
			return value;
		}

		public TextWriter getOutputStream()
		{
			return this.Response.Output;
		}
		
		public void sendDocument(Document d)
		{
			try {				
				if(d.mustBeTransformed) {
					Response.ContentType = Manager.i.config.GetValueOf("//Configuration/Views/View[@name='" + d.xslName + "']/@type");
					d.processToStream(this.Response.Output);
					Response.Flush();
				} else {
					Response.ContentType = "text/xml";
					Response.Output.Write(d.InnerXml);					
				}
			} catch(Exception e) {
				Manager.i.error("WebConnector", e);
			}			
		}
				
		public string getRemoteAddress()
		{
			return this.Request.UserHostAddress;			
		}						
		
		public string getLogParams()
		{
			string r = "";
			
			// TODO: catchup all params to string
			
			return r;			
		}						
				
		public HttpPostedFile getInputFile(string name)
		{
			return this.Request.Files[name];
		}
		
		public string getCookie(string name)
		{
			return this.Request.Cookies.Get(name).Value;
		}
		
		public void setCookie(string name, string value, int ttl)
		{
			try {
				HttpCookie cookie = new HttpCookie(name,value);
				cookie.Expires.AddMinutes(ttl);
				this.Response.SetCookie(cookie);
			} catch(Exception e) {
				Manager.i.error("WebConnector", e);
			}							
		}
	}
}
